'use strict';

const { app, protocol, BrowserWindow, session, ipcMain } = require('electron');
const path = require('path');
const isDevelopment = process.env.NODE_ENV !== 'production';
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');

const createVST3Parameter = (labelName, parameterId) => ({
    labelName,
    parameterId
});

const createVST3ParameterBank = () => {
    const parameterMap = new Map();

    return {
        // 添加参数
        addParameter: (labelName, parameterId) => {
            parameterMap.set(labelName, createVST3Parameter(labelName, parameterId));
        },

        // 获取参数
        getParameter: (labelName) => parameterMap.get(labelName),

        // 删除参数
        removeParameter: (labelName) => parameterMap.delete(labelName),

        // 获取所有参数
        getAllParameters: () => Array.from(parameterMap.values()),

        // 检查参数是否存在
        hasParameter: (labelName) => parameterMap.has(labelName),

        // 获取参数数量
        getParameterCount: () => parameterMap.size
    };
};

const parameterBank = createVST3ParameterBank();

protocol.registerSchemesAsPrivileged([
    { scheme: 'app', privileges: { secure: true, standard: true } }
]);

function createGrpcClient() {
    const PROTO_PATH = path.join(__dirname, 'protos/sushi_rpc.proto');
    const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
        keepCase: true,
        longs: String,
        enums: String,
        defaults: true,
        oneofs: true
    });
    const sushiProto = grpc.loadPackageDefinition(packageDefinition).sushi_rpc;
    return new sushiProto.ParameterController('172.16.3.26:51051', grpc.credentials.createInsecure());
}
async function createWindow() {
    const win = new BrowserWindow({
        width: 1920,
        height: 1080,
        resizable: false,
        frame: false,
        // fullscreen: true,
        titleBarStyle: 'hidden',
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js'),
            webviewTag: true,
            webSecurity: false, // 注意：在生产环境中应该避免禁用 webSecurity
            allowRunningInsecureContent: true
        }
    });

    // if (isDevelopment) {
        await win.loadURL('http://localhost:8080');
    //     win.webContents.openDevTools();
    // } else {
        // win.loadFile(path.join(__dirname, '../renderer/index.html'));
    // }

    win.webContents.openDevTools();

    const grpcClient = createGrpcClient();

    const hideScrollbarsCSS = 'html, body { overflow: hidden; }';
    win.webContents.on('did-finish-load', () => {
        win.webContents.insertCSS(hideScrollbarsCSS);
    });

    win.webContents.on('will-navigate', (event, url) => {
        // 如果需要，你可以在这里添加额外的导航控制
        console.log('Will navigate to:', url);
        win.webContents.insertCSS(hideScrollbarsCSS);
    });

    win.webContents.on('new-window', (event, url) => {
        // 阻止新窗口的打开，改为在当前窗口加载 URL
        event.preventDefault();
        win.loadURL(url);
    });

    win.webContents.on('did-finish-load', () => {
        win.webContents.insertCSS(hideScrollbarsCSS);
        win.webContents.send('enable-drag-navigation');
    });

    ipcMain.on('navigate', (event, direction) => {
        console.log('Main process received navigate command:', direction);
        const windows = BrowserWindow.getAllWindows();
        if (windows.length > 0) {
            const currentWindow = windows[0];
            currentWindow.webContents.send('change-page', direction);
        }
    });

    ipcMain.on('send-knob-value', (event, { knob, value }) => {
        if (!parameterBank.hasParameter(knob)) {
            console.error('Invalid knob:', knob);
            return;
        }
        const knobPara = parameterBank.getParameter(knob);
        var parameterValue = {
            parameter: {
                processor_id: 1,
                parameter_id: knobPara.parameterId,
            },
            value: value
        };

        console.log('Sending knob value:', knob, value);

        grpcClient.SetParameterValue(parameterValue, (error, response) => {
            if (error) {
                console.error('Error sending knob value:', error);
            } else {
                console.log('Knob value sent successfully:', parameterValue, response);
            }
        });
    });

    win.webContents.on('did-navigate', (event, url) => {
        console.log('Navigated to:', url);
    });

}

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

app.whenReady().then(() => {
    createWindow();

    session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
        callback({
            responseHeaders: {
                ...details.responseHeaders,
                'Content-Security-Policy': [
                    "default-src 'self' https://www.bilibili.com https://*.hdslb.com; " +
                    "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.bilibili.com https://*.hdslb.com; " +
                    "style-src 'self' 'unsafe-inline' https://www.bilibili.com https://*.hdslb.com; " +
                    "img-src 'self' data: https: http:; " +
                    "media-src 'self' data: blob: https: http:; " +  // 添加 blob:
                    "connect-src 'self' https: wss:; " +
                    "frame-src 'self' https://www.bilibili.com https://*.hdslb.com https://player.bilibili.com; " +
                    "object-src 'none'; " +  // 添加 object-src
                    "base-uri 'self'; "  // 添加 base-uri
                ]
            }
        });
    });

    parameterBank.addParameter("NOISE GATE", 1001);
    parameterBank.addParameter("DELAY", 1001);
    parameterBank.addParameter("REVERB", 1001);
    parameterBank.addParameter("INPUT", 3);
    parameterBank.addParameter("THRESHOLD", 15);
    parameterBank.addParameter("TIME", 7);
    parameterBank.addParameter("FEEDBACK", 9);
    parameterBank.addParameter("MIX", 13);
    parameterBank.addParameter("REVERB MIX", 16);
    parameterBank.addParameter("OUTPUT", 17);
});

if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit();
            }
        });
    } else {
        process.on('SIGTERM', () => {
            app.quit();
        });
    }
}